<template>
  <!-- 地区选择弹框 -->
  <uni-popup ref="regionPopup" type="bottom">
    <view class="region-picker-modal">
      <view class="picker-header">
        <text class="picker-cancel" @click="close">取消</text>
        <text class="picker-title">选择地区</text>
        <text class="picker-confirm" @click="confirmRegion">确认</text>
      </view>

      <!-- 三级联动选择器 -->
      <picker-view
        class="picker-view"
        :value="pickerValue"
        @change="pickerChange"
        :indicator-style="indicatorStyle"
      >
        <!-- 省 -->
        <picker-view-column>
          <view
            v-for="province in provinces"
            :key="province.value"
            class="picker-item"
          >
            <text class="picker-text">{{ province.text }}</text>
          </view>
        </picker-view-column>
        <!-- 市 -->
        <picker-view-column>
          <view v-for="city in cities" :key="city.value" class="picker-item">
            <text class="picker-text">{{ city.text }}</text>
          </view>
        </picker-view-column>
        <!-- 区 -->
        <picker-view-column>
          <view v-for="area in areas" :key="area.value" class="picker-item">
            <text class="picker-text">{{ area.text }}</text>
          </view>
        </picker-view-column>
      </picker-view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import { getProvinceData, getCityData, getAreaData } from "@/api/user";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ province: "", city: "", area: "" }),
  },
});

const emit = defineEmits(["update:modelValue", "confirm"]);

// 弹框引用
const regionPopup = ref(null);

// 临时选中的地区
const tempRegion = ref({
  province: "",
  provinceCode: "",
  city: "",
  cityCode: "",
  area: "",
  areaCode: "",
});

// 数据列表
const provinces = ref([]);
const cities = ref([]);
const areas = ref([]);
const pickerValue = ref([0, 0, 0]);
const indicatorStyle = "height: 50px;";

// 当前选中地区文本
const currentRegionText = computed(() => {
  if (!tempRegion.value.province) return "请选择地区";
  return `${tempRegion.value.province} / ${tempRegion.value.city} / ${tempRegion.value.area}`;
});

// 对外暴露方法
const open = () => {
  if (props.modelValue.province) {
    tempRegion.value = { ...props.modelValue };
    setPickerByRegion(props.modelValue);
  } else {
    // 默认选中第一个省市区
    setDefaultRegion();
  }
  regionPopup.value?.open();
};

const close = () => {
  regionPopup.value?.close();
};

defineExpose({ open, close });

// ==================== API 请求 ====================

// 获取省份列表
const { loading: provinceLoading, run: fetchProvinces } = useRequest(
  getProvinceData,
  {
    manual: true,
    onSuccess: (response) => {
      console.log("省份数据：", response);
      // 后端返回格式: { code: 2000, data: [...], message: '' }
      const data = response.data;
      if (data && Array.isArray(data)) {
        provinces.value = data.map((item) => ({
          text: item.AreaName,
          value: item.AreaId,
        }));
        console.log(
          "provinces.value 已更新，共",
          provinces.value.length,
          "个省份"
        );
        // 获取到省份后，获取第一个省的城市
        if (provinces.value.length > 0) {
          fetchCities(provinces.value[0].value);
        }
      }
    },
    onError: (error) => {
      console.error("获取省份数据失败：", error);
      uni.showToast({
        title: "获取省份数据失败",
        icon: "none",
      });
    },
  }
);

// 获取城市列表
const { loading: cityLoading, run: fetchCities } = useRequest(
  (provincialCode) => getCityData({ provincialCode }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("城市数据：", response);
      // 后端返回格式: { code: 2000, data: [...], message: '' }
      const data = response.data;
      if (data && Array.isArray(data)) {
        cities.value = data.map((item) => ({
          text: item.AreaName,
          value: item.AreaId,
        }));
        console.log("cities.value 已更新，共", cities.value.length, "个城市");
        // 获取到城市后，获取第一个城市的区县
        if (cities.value.length > 0) {
          fetchAreas(cities.value[0].value);
        }
      }
    },
    onError: (error) => {
      console.error("获取城市数据失败：", error);
    },
  }
);

// 获取区县列表
const { loading: areaLoading, run: fetchAreas } = useRequest(
  (cityCode) => getAreaData({ cityCode }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("区县数据：", response);
      // 后端返回格式: { code: 2000, data: [...], message: '' }
      const data = response.data;
      if (data && Array.isArray(data)) {
        areas.value = data.map((item) => ({
          text: item.AreaName,
          value: item.AreaId,
        }));
        console.log("areas.value 已更新，共", areas.value.length, "个区县");
        // 数据加载完成，更新临时选中数据
        updateTempRegion();
      }
    },
    onError: (error) => {
      console.error("获取区县数据失败：", error);
    },
  }
);

// 初始化数据
const initData = () => {
  // 从接口获取省份数据
  fetchProvinces();
};

// 更新城市列表
const updateCities = async (provinceIndex) => {
  const province = provinces.value[provinceIndex];
  if (province && province.value) {
    cities.value = [];
    areas.value = [];
    await fetchCities(province.value);
  } else {
    cities.value = [];
    areas.value = [];
  }
};

// 更新区县列表
const updateAreas = async (cityIndex) => {
  const city = cities.value[cityIndex];
  if (city && city.value) {
    areas.value = [];
    await fetchAreas(city.value);
  } else {
    areas.value = [];
  }
};

// 设置默认地区（第一个省市区）
const setDefaultRegion = async () => {
  // 默认选择第一个
  pickerValue.value = [0, 0, 0];
  // 如果已经有数据，更新临时选中
  if (
    provinces.value.length > 0 &&
    cities.value.length > 0 &&
    areas.value.length > 0
  ) {
    updateTempRegion();
  }
  // 否则数据会在 fetchAreas 的 onSuccess 中自动调用 updateTempRegion
};

// 滚轮变化
const pickerChange = async (e) => {
  const [pIdx, cIdx, aIdx] = e.detail.value;
  const oldValue = [...pickerValue.value];

  // 省份改变
  if (pIdx !== oldValue[0]) {
    pickerValue.value = [pIdx, 0, 0];
    await updateCities(pIdx);
    // 城市更新后，自动获取第一个城市的区县
    if (cities.value.length > 0) {
      await updateAreas(0);
    }
  }
  // 城市改变
  else if (cIdx !== oldValue[1]) {
    pickerValue.value = [pIdx, cIdx, 0];
    await updateAreas(cIdx);
  }
  // 区县改变
  else {
    pickerValue.value = [pIdx, cIdx, aIdx];
    updateTempRegion();
  }
};

// 更新临时地区数据
const updateTempRegion = () => {
  const [pIdx, cIdx, aIdx] = pickerValue.value;
  const province = provinces.value[pIdx];
  const city = cities.value[cIdx];
  const area = areas.value[aIdx];

  tempRegion.value = {
    province: province?.text || "",
    provinceCode: province?.value || "",
    city: city?.text || "",
    cityCode: city?.value || "",
    area: area?.text || "",
    areaCode: area?.value || "",
  };
};

// 根据地区设置选择器
const setPickerByRegion = async (region) => {
  const pIdx = provinces.value.findIndex((p) => p.text === region.province);
  if (pIdx !== -1) {
    await updateCities(pIdx);
    const cIdx = cities.value.findIndex((c) => c.text === region.city);
    if (cIdx !== -1) {
      await updateAreas(cIdx);
      const aIdx = areas.value.findIndex((a) => a.text === region.area);
      pickerValue.value = [pIdx, cIdx, aIdx !== -1 ? aIdx : 0];
    }
  }
  updateTempRegion();
};

// 确认选择
const confirmRegion = () => {
  emit("update:modelValue", { ...tempRegion.value });
  emit("confirm", { ...tempRegion.value });
  close();
};

onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.region-picker-modal {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.picker-cancel,
.picker-confirm {
  font-size: 28rpx;
  color: #ffa726;
}

.picker-title {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.picker-view {
  height: 400rpx;
  padding: 0 32rpx 32rpx;
}

.picker-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  padding: 0 10rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
  line-height: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  display: block;
  text-align: center;
}
</style>
